//
//  NewFeatureController.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/8/4.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let imageCount = 4
class NewFeatureController: UICollectionViewController {
    
    private let imageCount = 4
    
    private let layout = TSYFlowLayout()
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

       // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        let path = collectionView.indexPathsForVisibleItems().last!
        
        if path.item == imageCount - 1 {
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startAnimation()
        }
    }
}

class NewFeatureCell: UICollectionViewCell {
    /// 图像索引
    private var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startBtn.hidden = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareUI()
    }
    
    private func startAnimation() {
        startBtn.hidden = false
        startBtn.userInteractionEnabled = false
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startBtn.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                self.startBtn.userInteractionEnabled = true
        }
    }
    
    private func prepareUI() {
        //添加控件
        contentView.addSubview(iconView)
        contentView.addSubview(startBtn)
        
        iconView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
        
        startBtn.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        
        contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -180))
        
    }
    
    private lazy var iconView = UIImageView()
    
    private lazy var startBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        //btn.hidden = true
        btn.addTarget(self, action: "startExperience", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    
    }()
    
    //运行循环监听的,所以不能用private
    func startExperience() {
        NSNotificationCenter.defaultCenter().postNotificationName(TurnToMainContoller, object: true)
    }
        
}

private class TSYFlowLayout: UICollectionViewFlowLayout {
   
    /**  UICollectionViewFlowLayout 的属性
    var minimumLineSpacing: CGFloat
    var minimumInteritemSpacing: CGFloat
    var itemSize: CGSize
    @available(iOS 8.0, *)
    var estimatedItemSize: CGSize // defaults to CGSizeZero - setting a non-zero size enables cells that self-size via -preferredLayoutAttributesFittingAttributes:
    var scrollDirection: UICollectionViewScrollDirection // default is UICollectionViewScrollDirectionVertical
    var headerReferenceSize: CGSize
    var footerReferenceSize: CGSize
    var sectionInset: UIEdgeInsets
    */
    private override func prepareLayout() {
        itemSize = collectionView!.bounds.size
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
      //最后一个和第一个不反弹
        collectionView?.bounces = false
    }

}
